<template>
    <div class="collection">
        <div class="top-info">
            <div class="flex-box cells">
                <div class="cell">
                    签约编号：<span class="text">{{ detailInfo.applyCode }}</span>
                </div>
                <div class="cell">
                    签约主体：<span class="text">{{ detailInfo.signCompanyName }}</span>
                </div>
                <div class="cell">
                    销售名称：<span class="text">{{ detailInfo.salesName }}</span>
                </div>
            </div>
            <div class="flex-box cells mt10">
                <div class="flex">
                    <div class="flex-box">
                        <div class="cell large">
                            签约金额(元)：<span class="text">{{ numberToCurrencyNo(detailInfo.signAmount) }}</span>
                        </div>
                        <div class="cell large color">已回款金额：{{ numberToCurrencyNo(totalReceivable) }}
</div>
                    </div>
                </div>
                <!-- <el-button type="primary" @click="showMore = !showMore">
                    上传回款
                    <i class="el-icon--right" :class="showMore ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                </el-button> -->
            </div>
        </div>
        <div v-show="showMore" class="step">
            <el-steps direction="vertical" :active="1">
                <el-step title="上传回款凭证">
                    <template #description>
                        <div style="margin-bottom: 30px">
                            <xc-upload
                                ref="upload"
                                :limit="1"
                                accept=".jpg,.png"
                                :http-request="uploadFile"
                                tip="支持扩展名：jpg、png(限制附件1个)"
                                :history-length="credentials ? 1 : 0"
                                @on-remove="credentials = ''"
                            ></xc-upload>
                        </div>
                    </template>
                </el-step>
                <el-step title="填写回款金额">
                    <template #description>
                        <div class="flex-box">
                            <el-input
                                v-model="amount"
                                clearable
                                placeholder="请输入"
                                class="amount-input"
                                :disabled="credentials === ''"
                                oninput="value=value.replace(/[^0-9.]/g,'')"
                            />
                            <el-button
                                type="primary"
                                :disabled="credentials === '' || !amount"
                                :loading="upLoading"
                                @click="handleSave('add')"
                            >
                                确定
                            </el-button>
                        </div>
                    </template>
                </el-step>
            </el-steps>
        </div>
        <div class="table">
            <BasicTable
                :columns="columns"
                :table-data="tableData"
                :table-loading="tableLoading"
                :page-info="pageInfo"
                @onChangePage="(pageInfo: any) => searchList(pageInfo)"
            >
                <template #receivableMoney="{ row }">
                    <div v-if="!!row.receivableMoney" class="flex-box">
                        <div class="flex-shrink">
                            {{ numberToCurrencyNo(row.receivableMoney) }}
                        </div>
                        <el-popover
                            :visible="receivableId === row.receivableId && editType === 'num'"
                            effect="light"
                            trigger="click"
                            placement="top"
                            popper-class="xc-table-column-popper collection"
                        >
                            <template #default>
                                <el-input v-model="editVal" oninput="value=value.replace(/[^0-9.]/g,'')" />
                                <div class="edit-btns">
                                    <el-button size="small" @click="receivableId = -1"> 取消
</el-button>
                                    <el-button size="small" type="primary" :loading="editLoading" @click="handleSave">
                                        保存
                                    </el-button>
                                </div>
                            </template>
                            <template #reference>
                                <span>
                                    <edit class="edit" @click="handleShow(row)" />
                                </span>
                            </template>
                        </el-popover>
                    </div>
                </template>
                <template #credentials="{ row }">
                    <div v-if="!!row.credentials" class="flex-box align-items-center">
                        <el-image
                            :preview-teleported="true"
                            style="width: 48px; height: 48px"
                            :src="row.credentials"
                            fit="fit"
                            :preview-src-list="[row.credentials]"
                        />
                        <el-upload
                            accept=".jpg,.png"
                            :http-request="(file: File) => uploadFile(file, row )"
                            :show-file-list="false"
                            class="upload-demo"
                        >
                            <edit class="edit" />
                        </el-upload>
                    </div>
                </template>
                <template #updateTime="{ row }">
                    {{ formatDate2(row.updateTime, 'YYYY-MM-DD HH:mm:ss') }}
                </template>
            </BasicTable>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, onMounted, reactive, computed } from 'vue';
import xcUpload from '@x-tech/fe-pc-components/src/components/XcUpload/index.vue';
import BasicTable from '@/components/BasicTable.vue';
import { numberToCurrencyNo } from '@/utils/filters';
import { Edit } from '@element-plus/icons';
import { ElMessage } from 'element-plus';
import { getReceivableList, saveReceivable, getAllMoney } from '@/api/delivery/customerManage';
import { Upload } from '@x-tech/fe-puma-lib-upload';
import { useStore } from 'vuex';
import { formatDate2 } from '@x-tech/fe-utils/dist/date';

const upl = new Upload(window.XCConfig.VITE_ENV);
const store = useStore();
const userCode = computed(() => store.state.puma.user.code || '');
const groupCode = computed(() => store.state.userGroup.userInfo?.groupCode);
const credentials = ref('');
const upload = ref(null);
const upLoading = ref(false);
const editLoading = ref(false);
const editType = ref('');

const props = defineProps({
    detailInfo: {
        type: Object,
        default: () => {
            return {
                applyCode: '',
            };
        },
    },
});

const receivableId = ref(-1);
const amount = ref('');
const showMore = ref(true);

const tableData = ref([]);

const editVal = ref(0);

const totalReceivable = ref(0);

const tableLoading = ref(false);
const pageInfo = reactive({
    pageNum: 1,
    total: 0,
    pageSize: 10,
});

const columns = [
    { label: '回款金额', key: 'receivableMoney', render: true, prop: { width: '200px' } },
    { label: '凭证', key: 'credentials', render: true, prop: { width: '200px' } },
    { label: '操作人', key: 'userName' },
    { label: '操作时间', key: 'updateTime', render: true },
];

const handleShow = (row: any) => {
    editVal.value = row.receivableMoney;
    receivableId.value = row.receivableId;
    editType.value = 'num';
};

const searchList = async (pageObj: any) => {
    tableLoading.value = true;
    pageInfo.pageNum = pageObj?.pageNum ? pageObj?.pageNum : pageInfo.pageNum;
    pageInfo.pageSize = pageObj?.pageSize ? pageObj?.pageSize : pageInfo.pageSize;
    try {
        const data = await getReceivableList(Object.assign(pageInfo, { applyCode: props.detailInfo.applyCode }));
        tableData.value = data ? data.list : [];
        pageInfo.total = data ? data.total : 0;
    } finally {
        tableLoading.value = false;
    }
};

const init = async () => {
    searchList({});
    const data = await getAllMoney({
        applyCode: props.detailInfo.applyCode,
        joinTraderCode: props.detailInfo.joinTraderCode,
    });
    totalReceivable.value = data?.totalReceivable;
};

const handleSave = async (type: string) => {
    const params: any = {};
    // 新增的时候传  审批编码、凭证、加盟商编码、当前操作人的工号、回款、userNo（这个就是销售的工号）
    if (type === 'add') {
        params.applyCode = props.detailInfo.applyCode;
        params.actualContract = props.detailInfo.signAmount;
        params.credentials = credentials.value;
        params.joinTraderCode = groupCode.value;
        // params.joinTraderCode = 'test-join-demo';
        params.userNo = userCode.value;
        params.receivableMoney = amount.value;
        upLoading.value = true;
    } else if (type === 'edit') {
        params.userNo = userCode.value;
        params.receivableId = receivableId.value;
        params.credentials = credentials.value;
    } else {
        params.userNo = userCode.value;
        params.receivableId = receivableId.value;
        params.receivableMoney = editVal.value;
        editLoading.value = true;
    }
    try {
        await saveReceivable(params);
        receivableId.value = -1;
        pageInfo.pageNum = 1;
        credentials.value = '';
        amount.value = '';
        init();
        upload.value.$refs.elUpload.clearFiles();
    } catch (error) {
        console.log(error);
    } finally {
        upLoading.value = false;
        editLoading.value = false;
    }
};

const uploadFile = async (file: File, row: any) => {
    let _file: any = file;
    if (Array.isArray(file) && file.length) {
        _file = file[0];
    }
    try {
        const res = await upl.uploadWithoutFilename(_file.file!, false);
        credentials.value = res;
        if (row) {
            receivableId.value = row.receivableId;
            editType.value = 'img';
            handleSave('edit');
        }
        ElMessage.success('上传成功');
    } catch (error) {
        ElMessage.error('上传失败');
    }
};

onMounted(async () => {
    init();
});
</script>

<style lang="scss" scoped>
.flex-box {
    display: flex;
}
.flex {
    flex: 1;
}
.flex-shrink {
    flex-shrink: 0;
}
.align-items-center {
    align-items: center;
}
.top-info {
    .cells {
        align-items: center;
    }
    .cell {
        color: #8c8c8c;
        font-weight: 400;
        font-size: 14px;
        margin-right: 15px;
        position: relative;
        .text {
            color: #333;
        }
        &.large {
            font-size: 16px;
        }
        &.color {
            color: #333;
            font-weight: 700;
        }
    }
    .cell + .cell {
        margin-left: 15px;
        &::after {
            content: '';
            width: 1px;
            height: 14px;
            background-color: #ededed;
            position: absolute;
            left: -15px;
            top: 50%;
            transform: translateY(-40%);
        }
    }
}
.step {
    min-height: 213px;
    margin-top: 35px;
}

.amount-input {
    width: 284px;
    margin-right: 16px;
}
.table {
    margin-top: 33px;
}
::v-deep(.el-step__head .el-step__icon) {
    background-color: #fff;
    color: #e60044;
}
::v-deep(.el-step__line) {
    background-color: rgba(230, 0, 68, 0.2);
}
::v-deep(.el-step__title) {
    color: #333;
    font-size: 16px;
    font-weight: 400;
    margin-bottom: 16px;
}
.edit {
    width: 3em;
    height: 1em;
    position: relative;
    top: 2px;
    cursor: pointer;
}

.mt10 {
    margin-top: 10px;
}
.upload-demo {
    width: 48px;
}
</style>

<style lang="scss">
.xc-table-column-popper.collection {
    width: auto !important;
}
</style>
